<template>
  <div v-if="is_info" v-html="value"></div>
  <div v-else class="form_item-editor">
    <input type="file" ref="wechat_img" style="display: none" accept="image/jpeg,image/png,image/gif" @change="upload_wechat_img">
    <textarea class="editor-inner" ref="editor" spellcheck="false" :name="name" :value="value"></textarea>
  </div>
</template>

<script>
import Editor from 's94-editor'
import {ajax} from "@/js/api_tool.js";
export default {
  _title_: '编辑器(微信)',
  name: "editor",
  props: ['name', 'value', 'config', 'is_info', 'size', 'is_list'],
  emits: ['update:value', 'change'],
  data(){
    return {
      need_display: true, //是否需要渲染
    }
  },
  methods: {
    update_value(value, need_display){
      let app = this;
      if (!need_display){
        app.need_display = false;
        setTimeout(function (){app.need_display = true;},5)
      }
      this.$emit('update:value', value);
      this.$emit('change', value);
    },
    upload_wechat_img(e){
      let app = this;
      var dom = e.target;
      var fd = new FormData();
      fd.append('file', dom.files[0]);
      ajax({url:'/admin/file/uploadimg_wechat',data: fd,method:'POST'}, function (res){
        app.editor.execCommand('insertHTML', `<img src="${res.data.url}" style="max-width: 100%;" referrerpolicy="no-referrer">`);
        dom.value = '';
      }, function (){
        dom.value = '';
      })
    },
  },
  watch: {
    value(){
      if (!this.need_display || !this.editor) return;
      setTimeout(()=>{
        this.editor.updateHtml();
        this.editor.lastRow();
      },5)
    },
  },
  mounted() {
    let app = this;
    if (this.is_info) return;
    var editor_config = {}

    Editor.Menu.menuList.image.onclick = function (menu){
      app.$refs['wechat_img'].click();
    }
    if (this.config){
      editor_config.menus = this.config.toString().split(',')
    }

    this.editor = new Editor(this.$refs.editor, editor_config);

    this.editor.container.addEventListener('input', function (){
      app.update_value(app.editor.html());
    });
    this.editor.textarea.addEventListener('change', function (){
      app.update_value(app.editor.html());
    });
  }
}
</script>

<style scoped>
.form_item-editor{width: 650px;padding: 04px;border-radius: 04px;border: solid 01px var(--sm_bg);outline: 0;}
.form_item-editor .editor-inner{display: block;width: 100%;min-height: 400px;outline: none;resize: none;}
</style>